package com.kert.word.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;


@Service
@Slf4j
public class DocxServiceImpl implements DocxService{
    @Override
    public void readDoc(InputStream inputStream) throws IOException, OpenXML4JException, ParserConfigurationException, SAXException, TransformerException {
        log.info("read doc");
        XWPFDocument xwp = new XWPFDocument(inputStream);
        List<PackagePart> allEmbeddedParts = xwp.getAllEmbeddedParts();
        for (PackagePart emb : allEmbeddedParts) {
            System.out.println(emb);
            POIFSFileSystem fs = new POIFSFileSystem(emb.getInputStream());
            DirectoryNode root = fs.getRoot();
            DocumentEntry entry = (DocumentEntry) root.getEntry("Equation Native");
            byte[] data = new byte[entry.getSize()];
            try (OutputStream out = new FileOutputStream("image.png")) {
                out.write(data);
            }
        }
    }
}
